const { exec } = require('child_process');

// 新建L2TP连接
function createL2TPConnection(serverIP, username, password) {
    const command = `Add-VpnConnection -Name "L2TP Connection" -ServerAddress ${serverIP} -TunnelType L2tp -EncryptionLevel Optional -AuthenticationMethod MSChapv2 -RememberCredential -SplitTunneling -AllUserConnection -L2tpPsk ${password} -PassThru`;

    exec(`powershell.exe -Command "${command}"`, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error creating L2TP connection: ${error.message}`);
            return;
        }
        console.log(`L2TP connection created successfully: ${stdout}`);
    });
}

// 连接L2TP连接
function connectL2TPConnection() {
    const command = `rasdial "L2TP Connection" ${username} ${password}`;

    exec(`cmd.exe /c "${command}"`, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error connecting L2TP connection: ${error.message}`);
            return;
        }
        console.log(`L2TP connection established: ${stdout}`);
    });
}

// 断开L2TP连接
function disconnectL2TPConnection() {
    const command = `rasdial "L2TP Connection" /disconnect`;

    exec(`cmd.exe /c "${command}"`, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error disconnecting L2TP connection: ${error.message}`);
            return;
        }
        console.log(`L2TP connection disconnected: ${stdout}`);
    });
}

// 使用示例
const serverIP = '43.134.189.46';
const username = 'ceshi';
const password = 'ceshi';

createL2TPConnection(serverIP, username, password);
connectL2TPConnection();
// 在需要时调用disconnectL2TPConnection()来断开连接
